<template>
  <div class="page_body">
    <HomeTop :topTitle="topTitle"></HomeTop>
    <div class="page_box">
      <div class="page_type" v-if="orderStatus == 2">
        <div class="imgBox">
          <img
            class="img_type"
            src="../../assets/image/success_icon03.png"
            alt=""
          />
          <div class="img_title">待支付</div>
        </div>
        <div class="remain_time"><span>剩余时间:{{countdownText}}</span></div>
      </div>
      <div class="page_theme">
        <div class="theme_head">
          <img class="theme_img" :src="this.recordlist.image_path" alt="" />
          <div class="theme_title">{{ this.recordlist.title }}</div>
        </div>
        <div class="theme_center">
          <img
            class="time_icon"
            src="../../assets/image/time_icon01.png"
            alt=""
          />
          <div class="time">{{ this.recordlist.start_date }}</div>
          <div v-if="orderStatus == 1" class="price">
            ￥{{ this.recordlist.money * teamList.amount }}.00
          </div>
          <div v-if="orderStatus == 2" class="price">
            ￥{{ this.recordlist.money }}
          </div>
        </div>
        <div class="theme_address">
          <img
            class="address_icon"
            src="../../assets/image/address_icon01.png"
            alt=""
          />
          <div class="address">{{ this.recordlist.address }}</div>
        </div>
      </div>
      <div class="page_msg">
        <img
          @click="openDialog()"
          class="to_icon"
          src="../../assets/image/to_icon03.png"
          alt=""
        />
        <div class="msg_head">报名信息</div>
        <div class="msg">队伍名称：{{ this.teamList.name }}</div>
        <div class="msg">队伍人数：{{ this.teamList.amount }}</div>
        <div class="msg">领队：{{ this.teamList.leader_name }}</div>
        <div class="msg">教练：{{ this.teamList.leader_name }}</div>
        <div class="msg">队员名单：{{ this.teamList.player_name }}</div>
      </div>
      <van-dialog
        width="90%"
        class="memberListDialog"
        v-model="diolagShow"
        title="队员名单"
        :showConfirmButton="false"
      >
        <img
          @click="closeDiolag()"
          class="closeIcon"
          src="../../assets/image/close_icon01.png"
          alt=""
        />
        <div class="diolag_content">
          <div class="listBox" v-for="(item, index) in players" :key="index">
            <div>
              <p>姓名</p>
              {{ item.name }}
            </div>
            <div>
              <p>证件类型</p>
              {{ indentity[item.identity_type] }}
            </div>
            <div>
              <p>证件号码</p>
              {{ item.identity_number }}
            </div>
            <div>
              <p>性别</p>
              {{ item.sex }}
            </div>
            <div>
              <p>年龄（岁）</p>
              {{ item.age }}
            </div>
          </div>
        </div>
      </van-dialog>
      <div class="page_serve">
        <div class="serve_head">增值服务</div>
        <div class="serve" v-for="(item, index) in goodsList" :key="index">
          <div class="serve_left">
            <div class="check_box" v-if="orderStatus == 1">
              <van-checkbox
                v-model="item.selected"
                :disabled="item.is_required == 1"
              ></van-checkbox>
            </div>

            <div class="serve_type">{{ item.name }}</div>
            <div class="price">¥{{ item.money }}</div>
            <div v-if="orderStatus == 2">*{{ item.amount }}</div>
          </div>
          <div class="adjustNum" v-if="orderStatus == 1">
            <van-stepper
              min="0"
              disable-input
              v-model="item.count"
              :disabled="item.is_required == 1"
              integer
            />
          </div>
        </div>
      </div>
    </div>
    <div style="height: 2.2rem"></div>
    <div class="page_bottom">
      <div class="togeter">合计:</div>
      <div v-if="orderStatus==1" class="price">￥{{ togeterNum }}.00</div>
      <div v-if="orderStatus==2" class="price">￥{{recordlist.total_money}}</div>
      <div class="btn">
        <div v-if="orderStatus == 1" class="cancel" @click="cancel()">
          取消报名
        </div>
        <div v-if="orderStatus == 2" class="cancel" @click="cancelApply()">
          取消支付
        </div>
        <div class="apply" v-if="orderStatus == 1" @click="createEnrollOrder()">立即支付</div>
        <div class="apply" v-if="orderStatus == 2" @click="payBtnFn()">立即支付</div>
      </div>
    </div>
  </div>
</template>

<style src="../../assets/css/game/applyDetails.css" scoped></style>

<script>
import HomeTop from "@/components/homeTop.vue";
import { MessageBox, Indicator, Toast } from "mint-ui";
// import { Router } from "express";
import { Checklist } from "mint-ui";
import { Stepper, Checkbox, Dialog } from "vant";
import "vant/lib/stepper/style";

export default {
  name: "addMember",
  components: {
    HomeTop,
    Checklist,
    [Stepper.name]: Stepper,
    [Checkbox.name]: Checkbox,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      diolagShow: false, //队员详情弹窗显示状态
      topTitle: "报名详情", // 顶部组件参数设置
      optionValue: true,
      recordlist: {}, //活动详情（时间/地址等数据）
      teamList: {}, //队伍的报名信息
      players: {}, //队员名单
      goodsList: [], //增值服务列表
      countdownText: "", //订单剩余时间
      remain_time:"0分0秒",//支付倒计时显示文本
      orderId: "", //订单ID
      orderStatus: "1", //订单支付：1  待支付：2
      indentity: {
        1: "身份证",
        2: "护照 ",
        3: "港、澳、台胞证件",
        4: "其它",
      }, //证件号枚举
    };
  },
  // created(){},
  mounted() {
    Indicator.open();
    this.orderId = this.$route.query.orderId;
    if (this.orderId) {
      this.getUnpaidList();
    } else {
      this.getServeList();
      this.getlist();
    }
    Indicator.close();
  },
  computed: {
    togeterNum() {
      let totalPrice = Number(this.recordlist.money) * this.teamList.amount;
      let arr = this.goodsList.filter((e) => e.selected == true);
      for (let i = 0; i < arr.length; i++) {
        totalPrice += arr[i].money * arr[i].count;
      }
      return totalPrice;
    },
  },
  methods: {
    // 设置订单剩余时间
    setOrderTimeFn: function () {
      let that = this;
      this.orderInterval = setInterval(function () {
        let time = that.remain_time;
        if (time >= 0) {
          let minute = 0;
          if (time >= 60) {
            minute = parseInt(time / 60);
            time = parseInt(time % 60);
          }
          that.countdownText = minute + "分" + time + "秒";
          that.remain_time = that.remain_time - 1;
        } else {
          that.singelOrderOverdueDealFn();
          clearInterval(that.orderInterval);
        }
      }, 1000);
    },
    // 订单超时处理
    singelOrderOverdueDealFn: function () {
      let that = this;
      Indicator.open();
      let url = "/mobile/cancelEnrollByExpire";
      let data = {
        order_id: this.orderId,
      };
      this.axios
        .post(url, data)
        .then((response) => {
          if (response.code == 0) {
            Toast({
              message: "超出支付时间",
              duration: 3000,
            });
            that.$router.replace({
              name: "gameCenter",
            });
          } else {
            Toast({
              message: response.msg,
              duration: 3000,
            });
          }
          Indicator.close();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    //获取增值服务信息
    getServeList() {
      let url = "/mobile/eventDetail";
      let data = {
        event_id: sessionStorage.getItem("id"),
      };
      Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          Indicator.close();
          if (res.code == 0) {
            this.recordlist = res.record;
            // this.togeterNum = Number(this.recordlist.money);
            this.goodsList = res.goods;
            this.goodsList.forEach((e) => {
              if (e.is_required == 1) {
                e.count = this.teamList.amount;
                // console.log(e.coun);
              }
            });
          }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    //获取队伍信息
    getlist() {
      // console.log(this.$route.query);
      let url = "/mobile/teamDetail";
      let data = {
        team_id: this.$route.query.id,
      };
      Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          Indicator.close();
          if (res.code == 0) {
            this.teamList = res.team;
            this.players = res.player;
            // this.getTeamList();
          }else{
            Toast({
              message: res.msg,
              duration: 3000,
            });
          }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    //获取待支付详情
    getUnpaidList() {
      this.orderStatus = 2;
      let url = "/mobile/orderDetail";
      let orderId = this.$route.query.orderId;
      //如果从报名列表页面进入 orderId为传过来的OrderId
      if (orderId) {
        this.orderId = orderId;
      }
      let data = {
        order_id: this.orderId,
      };
      Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          Indicator.close();
          if (res.code == 0) {
            this.teamList = res.enroll_detail;
            this.teamList.name = res.enroll_detail.team_name
            this.recordlist.money = res.enroll_detail.money;
            this.recordlist.title = res.enroll_detail.title;
            this.recordlist.total_money = res.enroll_detail.total_money;
            this.recordlist.address = res.enroll_detail.address;
            this.recordlist.image_path = res.enroll_detail.image_path;
            this.recordlist.start_date = res.enroll_detail.start_date;
            this.remain_time = res.remain_time
            this.goodsList = res.goods;
            this.players = res.player;
            this.goodsList.forEach((e) => {
              if (e.is_required == 1) {
                e.count = this.teamList.amount;
                // console.log(e.coun);
              }
            });
            this.setOrderTimeFn()
            // console.log("111", res);
          }else{
            Toast({
              message: res.msg,
              duration: 3000,
            });
          }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    //关闭弹窗
    closeDiolag() {
      this.diolagShow = false;
    },
    //打开弹窗
    openDialog() {
      this.diolagShow = true;
    },
    //取消报名按钮
    cancel() {
      MessageBox({
        message: "确认取消报名?",
        confirmButtonText: "确认",
        showCancelButton: true,
      }).then((action) => {
        if (action == "confirm") {
          this.$router.push({
            name: "gameCenter",
          });
        }
      });
    },
    //取消支付按钮
    cancelApply() {
      MessageBox({
        message: "确认取消报名?",
        confirmButtonText: "确认",
        showCancelButton: true,
      }).then((action) => {
        if (action == "confirm") {
          let url = "/mobile/cancelEnroll";
          let data = {
            order_id: this.orderId,
          };
          Indicator.open();
          this.axios
            .post(url, data)
            .then((response) => {
              if ((response.code == 0)) {
                this.$router.push({
                  name: "gameCenter",
                });
              } else {
                Toast({
                  message: res.msg,
                  duration: 3000,
                });
              }
              Indicator.close();
            })
            .catch(function (error) {
              console.log(error);
            });
        }
      });
    },
    //点击立即支付  跳转到支付详情或者待支付页面
    createEnrollOrder() {
      // this.toSuccessFn()
      // console.log('8978');
      let url = "/mobile/createEnrollOrder";
      let data = {
        event_id: sessionStorage.getItem("id"),
        team_id: this.$route.query.id,
        goods: this.goodsList,
      };
      Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          Indicator.close();
          if (res.code == 0) {
            this.orderId = res.order_id;
            this.payBtnFn();
            // this.toSuccessFn()
          } else {
            Toast({
              message: res.msg,
              duration: 3000,
            });
          }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    // 支付按钮
    payBtnFn: function () {
      // console.log(this.orderId);
      let that = this;
      let url = "/wechatpay/createOrderJs";
      let data = {
        order_id: this.orderId,
        type: 1,
      };
      Indicator.open("请稍等...");
      this.axios
        .post(url, data)
        .then((response) => {
          Indicator.close();
          if (response.code == 0) {
            that.payFn(response);
          } else {
            Toast({
              message: response.msg,
              duration: 3000,
            });
          }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    // 调起支付
    payFn: function (data) {
      let that = this;
      let payData = data;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady(payData),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent(
            "WeixinJSBridgeReady",
            that.onBridgeReady(payData)
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            that.onBridgeReady(payData)
          );
        }
      } else {
        this.onBridgeReady(payData);
      }
    },
    // 微信支付
    onBridgeReady: function (payData) {
      let that = this;
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: payData.appId, //公众号ID，由商户传入
          timeStamp: payData.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: payData.nonceStr, //随机串
          package: payData.package,
          signType: payData.signType, //微信签名方式：
          paySign: payData.paySign, //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            that.toSuccessFn();
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            that.cancelPay();
          }
        }
      );
    },
    // 跳转至订单完成提示页
    toSuccessFn: function () {
      // console.log("444", this.orderId);
      let that = this;
      this.$router.replace({
        name: "applySuccess",
        query: {
          orderId: that.orderId,
          source: "eventPay",
        },
      });
    },
    // 用户微信取消支付
    cancelPay: function () {
      this.orderStatus = 2;
      let url = "/wechatpay/cancelOrderPay";
      let data = {
        order_id: this.orderId,
      };
      Indicator.open();
      this.axios
        .post(url, data)
        .then((response) => {
          if (response.code != 0) {
            Toast({
              message: response.msg,
              duration: 3000,
            });
            // this.setOrderTimeFn()
          }else{
            this.getUnpaidList()
          }
          Indicator.close();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
  // computed: {
  //   change(e) {
  //     console.log(e, "eeee");
  //     this.goodsList.forEach((ele) => {
  //       console.log(ele.money);
  //       this.togeterNum = ele.money * e;
  //     });
  //   },
  // },
};
</script>
<style>
.van-dialog__header {
  font-size: 0.3rem;
  font-weight: 700;
}
</style>
